import { _decorator, Button, Component, director, EventTouch, Label, Node, sys } from 'cc';
import { GameMainController } from './GameMainController';
import { AudioMgr } from './AudioMgr';
import { LocalStorageKey } from './ConstValue';
const { ccclass, property } = _decorator;

@ccclass('GameOverController')
export class GameOverController extends Component {

    @property(Button)
    private restartBtn: Button = null
    @property(Button)
    private backBtn: Button = null
    @property(Label)
    private scoreLable: Label = null
    @property(Label)
    private goldLable: Label = null
    @property(Node)
    private bg: Node = null

    private score: number = 0
    private gold: number = 0
    private controller: GameMainController = null

    public setController(controller) {
        this.controller = controller;
    }

    start() {
        this.bg.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
    }

    onTouchStart(event: EventTouch) {
        // 阻止事件继续向下传递
        event.propagationStopped = true;
    }

    onDestroy() {
        // 移除监听以避免内存泄漏
        this.node.off(Node.EventType.TOUCH_START, this.onTouchStart, this);
    }

    onEnable() {
        console.debug("game over onEnable")
        let passedParams = window.globalParam;
        if (passedParams) {
            window.globalParam = null
            this.score = passedParams.score;
            this.gold = passedParams.gold;
        }
        this.scoreLable.string = this.score + ""
        this.goldLable.string = this.gold + ""
        this.updataGoldAndScore();
        this.restartBtn.node.on(Button.EventType.CLICK, this.restartGame, this);
        this.backBtn.node.on(Button.EventType.CLICK, this.backMain, this);
    }

    onDisable() {
        this.score = 0;
        this.gold = 0;
    }


    update(deltaTime: number) {

    }

    public restartGame() {
        AudioMgr.inst.playOneShot("musics/click.bubble")
        if (this.controller) {
            this.controller.restartGame();
        }
    }

    public backMain() {
        AudioMgr.inst.playOneShot("musics/click.bubble")
        window.globalParam = {
            sceneName: "HomeScene"
        };
        director.loadScene("LoadingScene")
    }

    public updataGoldAndScore() {
        let score = sys.localStorage.getItem(LocalStorageKey.SCORE)
        if (score == null) {
            sys.localStorage.setItem(LocalStorageKey.SCORE, this.score + "")
        } else if (score && this.score > Number(score)) {
            sys.localStorage.setItem(LocalStorageKey.SCORE, this.score + "")
        }
        let goldNum = sys.localStorage.getItem(LocalStorageKey.GOLD)
        if (goldNum) {
            let sumGoldNum: number = Number(goldNum) + Number(this.gold)
            sys.localStorage.setItem(LocalStorageKey.GOLD, sumGoldNum + "")
        } else {
            sys.localStorage.setItem(LocalStorageKey.GOLD, this.gold + "")
        }
    }

}


